=begin

This file is part of the RSIF project, http://rsif.googlecode.com

Copyright (c) 2009-2009 Roberto Dario Seminara <robertodarioseminara@gmail.com>

rsif is free software: you can redistribute it and/or modify
it under the terms of the gnu general public license as published by
the free software foundation, either version 3 of the license, or
(at your option) any later version.

rsif is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.  see the
gnu general public license for more details.

you should have received a copy of the gnu general public license
along with rsif.  if not, see <http://www.gnu.org/licenses/>.
=end

module Rsif
module Core

class Logger

	@@severity = { 
		:debug => 0, 
		:info => 1, 
		:warn => 2, 
		:error => 3, 
		:fatal => 4, 
		:unknown => 5 }

	attr_accessor	:level
	attr_accessor	:output_proc
	
	@@severity.each do |sevname,sevlevel|
		eval("#{sevname.to_s.upcase} = #{sevlevel}")
	end

	def initialize( *args )
		 @output_proc = args.find{ |x| x.instance_of? Proc } || proc do |m| print m,"\n" end
		 @level = args.find{ |x| x.instance_of? Fixnum } || INFO

		@@severity.each do |sevname,sevlevel|
			eval("
			def self.#{sevname}(message = \"\")
				if block_given?
					log_i(#{sevlevel}, '#{sevname.to_s.upcase}') do
						yield
					end
				else
					log_i(#{sevlevel}, message, '#{sevname.to_s.upcase}')
				end
			end
			")
		end
		
	end

	def log(severity, arg2 = nil, arg3 = nil)
		if block_given?
			log_i(severity, arg2, arg3) do
				yield
			end
		else
			log_i(severity, arg2, arg3)
		end
	end
	
	private
	def log_i(severity, arg2, arg3 = nil)
		if (severity >= self.level)

			if block_given?
				message = yield
				messagetype = arg2 || "VERB#{severity}"
			else
				message = arg2
				messagetype = arg3 || "VERB#{severity}"
			end

			trace_details = messagetype + " " + call_details
	
			lenrelleno = (45-trace_details.length)
			lenrelleno = 0 if lenrelleno < 0
			relleno = " "*lenrelleno

			self.output_proc.call("#{trace_details}#{relleno}:#{message}")
		end
	end

	def call_details
		begin
			raise "0"
			""
		rescue Exception => e
			process_call_details( e.backtrace[3] )
		end
	end

	def process_call_details( a )
		twopoints = a.split(":")
		"#{twopoints[0].split(/\/|\\/)[-1]}:#{twopoints[1]} #{twopoints[2]}"
	end



end

end
end

